//
//  PhotoBrowerCollectionViewCell.swift
//  WB
//
//  Created by leador on 17/5/18.
//  Copyright © 2017年 袁满. All rights reserved.
//

import UIKit
import SDWebImage

class PhotoBrowerCollectionViewCell: UICollectionViewCell {
    
    var picUrl : URL? {
        
        didSet {
            
            guard let picUrl = picUrl else {
                return
            }
            
            let image = SDWebImageManager.shared().imageCache?.imageFromCache(forKey: picUrl.absoluteString)
            
            let width : CGFloat = kScreenWidth
            let height : CGFloat = width/(image?.size.width)! * (image?.size.height)!
            var y : CGFloat = 0
            if height < kScreenHeight {
                y = (kScreenHeight - height) * 0.5
            }
            
            imageView.frame = CGRect(x: 0, y: y, width: width, height: height)
            
            progressView.isHidden = false
            let largeImageUrl = NSURL(string:picUrl.absoluteString.replacingOccurrences(of: "thumbnail", with: "large"))
            imageView.sd_setImage(with: largeImageUrl as URL?, placeholderImage: image, options: [], progress: { (current, total, _) in
                
                self.progressView.progress = CGFloat(current) / CGFloat(total)
                
            }) { (_, _, _, _) in
                
                self.progressView.isHidden = true
            }
            
            scrollView.contentSize = CGSize(width: 0, height: kScreenHeight)
            
        }
        
    }
    lazy var scrollView : UIScrollView = UIScrollView()
    lazy var imageView : UIImageView = UIImageView()
    lazy var progressView : ProgressView = ProgressView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension PhotoBrowerCollectionViewCell {
    
    func setupUI() {
    
        contentView.addSubview(scrollView)
        contentView.addSubview(progressView)
        scrollView.addSubview(imageView)
        
        scrollView.frame = contentView.bounds
        progressView.bounds = CGRect(x: 0, y: 0, width: 50, height: 50)
        progressView.center = CGPoint(x: kScreenWidth*0.5, y: kScreenHeight*0.5)
        
        progressView.isHidden = true
        progressView.backgroundColor = .clear
        
    }
    
}
